package com.v1.video.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;

import com.iss.view.pulltorefresh.PullToRefreshBase;
import com.iss.view.pulltorefresh.PullToRefreshBase.Mode;
import com.iss.view.pulltorefresh.PullToRefreshBase.OnRefreshListener2;
import com.iss.view.pulltorefresh.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.adapter.SecondAdapter2;
import com.v1.video.domain.SecondEntity;
import com.v1.video.httpApi.V1VideoHttpApi;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.util.Helper;
import com.v1.video.util.Logger;

public class SecondFragment extends V1BaseFragment {

	private final String TAG = "SecondFragment";
	private View mView, mEmptyView;
	private LayoutInflater mInflater;
	private PullToRefreshListView mRefreshListView;
	private ListView mListView;
	private SecondAdapter2 mAdapter;
	private int mCurIndex = 1;
	private int mLstPosition = -1;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		mView = inflater.inflate(R.layout.fragment_recommend, container, false);
		initView();
		setListener();
		initData();
		return mView;
	}

	private void initView() {
		mEmptyView = mInflater.inflate(R.layout.fragment_no_content, null);
		mRefreshListView = (PullToRefreshListView) mView
				.findViewById(R.id.lv_listView);
		mListView = mRefreshListView.getRefreshableView();
		mRefreshListView.setMode(Mode.PULL_FROM_START);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void setListener() {
		mEmptyView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mRefreshListView != null) {
					mRefreshListView.doPullRefreshing(100);
				}
			}
		});

		mRefreshListView.setOnRefreshListener(new OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				mCurIndex = 1;
				if (Helper.checkConnection(getActivity())) {
					getServerData();
				} else {
					mHandler.sendEmptyMessageDelayed(0, 100);
				}
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				if (Helper.checkConnection(getActivity())) {
					getServerData();
				} else {
					mHandler.sendEmptyMessageDelayed(0, 100);
				}
			}
		});

		mListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					ImageLoader.getInstance().resume();
					if (mAdapter != null && mAdapter.getCurIndex() != -1) {
						int index = mAdapter.getCurIndex();
						if (mLstPosition != index) {
                            if (mAdapter != null) {
                            	mAdapter.release();
                                mAdapter.setCurIndex(mLstPosition);
                                mAdapter.notifyDataSetChanged();
                            }
                        }
					}
					break;
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
					ImageLoader.getInstance().pause();
					break;
				case OnScrollListener.SCROLL_STATE_FLING:
					ImageLoader.getInstance().pause();
					break;
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "firstVisibleItem=" + firstVisibleItem
                        + "--visibleItemCount=" + visibleItemCount
                        + "--totalItemCount=" + totalItemCount);
                mLstPosition = firstVisibleItem;
			}
		});
	}

	private void initData() {
		mAdapter = new SecondAdapter2(getActivity());
		mListView.setAdapter(mAdapter);
		if (mRefreshListView != null) {
			mRefreshListView.doPullRefreshing(100);
		}
	}

	private void getServerData() {
		String url = String.format(V1VideoHttpApi.SECOND_LIST(), mCurIndex,
				Constant.DEVICEID);
		Logger.i(TAG, "获取秒评列表url=" + url);
		RequestManager.getInstance().getRequest(this.getActivity(), url,
				SecondEntity.class, new OnResponseListener() {

					@Override
					public void onSuccess(Object object, int code,
							String message, String keyId) {
						// TODO Auto-generated method stub
						if (mRefreshListView != null) {
							mRefreshListView.onRefreshComplete();
						}
						try {
							if (object != null) {
								SecondEntity entity = (SecondEntity) object;
								if (entity != null && entity.getBody() != null) {
									if (mAdapter != null) {
										if (mCurIndex == 1) {
											mAdapter.clearLstData();
											mAdapter.setCurIndex(0);
										}
										mAdapter.setLstData(entity.getBody()
												.getList());
									}
									int countNum = mCurIndex
											* entity.getBody().getOffset();
									if (countNum < entity.getBody()
											.getRecordCount()) {
										mCurIndex++;
										if (mRefreshListView != null) {
											mRefreshListView.setMode(Mode.BOTH);
										}
									} else {
										if (mRefreshListView != null) {
											mRefreshListView
													.setMode(Mode.PULL_FROM_START);
										}
									}
								} else {
									setEmptyView();
								}
							}
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						if (mRefreshListView != null) {
							mRefreshListView.onRefreshComplete();
						}
						setEmptyView();
						Logger.i(TAG, message);
					}

				});
	}
	
	/**
	 * 设置空的界面显示
	 */
	private void setEmptyView() {
		View view = mListView.getEmptyView();
		if (view == null) {
			mListView.setEmptyView(mEmptyView);
		}
	}
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				if (mRefreshListView != null) {
					mRefreshListView.onRefreshComplete();
				}
				setEmptyView();
				showToast(R.string.net_no_click);
				break;
			default:
				break;
			}
		}
	};
}
